import {Category_model} from 'category_model.js';

var category_model = new Category_model();


Page({
  data: {
    transClassArr: ['tanslate0', 'tanslate1', 'tanslate2', 'tanslate3', 'tanslate4', 'tanslate5'],
    currentMenuIndex: 0,
    loadingHidden:false
  },


  onLoad:function (options) {
    this._loadData();
  },

  _loadData:function () {
    var that = this;

    //获取所有分类
    category_model.getCategories((categoryData) => {
      that.setData({
        'categoryArr': categoryData
      });

      //获取分类商品,默认获取第一个分类商品
      that.getProductsByCategory(categoryData[0].id, (data) => {
        // console.log(categoryData);
        var dataObj = {
          procucts: data,
          topImgUrl: categoryData[0].img.url,
          title: categoryData[0].name
        };

        that.setData({
          loadingHidden: true,
          categoryInfo0: dataObj
        });

      });


    });
  },

  //到达详情页
  onProductsItemTap: function (event) {
    var categoryId = category_model.getDataSet(event, 'id');
    console.log(categoryId);
    wx.navigateTo({
      url: '../product/product?id=' + categoryId,
    })
  },

  getProductsByCategory:function (id, callback) {
    category_model.getProductsByCategory(id, (data) => {
      callback && callback(data);
    });
  },

  //点击菜单
  changeCategory:function(event) {
    var index = category_model.getDataSet(event, 'index'),
        id = category_model.getDataSet(event, 'id');

    this.setData({
      currentMenuIndex:index
    });

    //如果是之前请求了数据，则不再进行请求
    if (this.data['categoryInfo' + index]) {
      return;
    }

    //请求分类数据
    this.getProductsByCategory(id, (data) => {
      var dataObj = {
        procucts: data,
        topImgUrl: this.data.categoryArr[index].img.url,
        title: this.data.categoryArr[index].name
      };
      // console.log(dataObj);

      var obj = {};
      obj['categoryInfo' + index] = dataObj;
      obj['loadingHidden'] = true;
      this.setData(obj);
    });


  },

  //设置页面的分享信息
  onShareAppMessage: function () {
    return {
      title: "萌店",
      desc: "朋友圈的品质生活",
      path: "pages/category/category"
    }
  }
});